package com.wxy.web.security.authentication;

import com.alibaba.fastjson.JSONObject;
import com.wxy.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    private AuthenticationManager authenticationManager;

    public JwtLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    /**
     * 请求登录
     *
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = "";
        String password = "";
        ValidResult validResult = new ValidResult();

        try {
            JSONObject json = GetRequestJsonUtil.getRequestJsonObject(request);
            username = json.getString("username");
            password = json.getString("password");
        } catch (Exception e) {
            validResult.fail("", "Error", "参数格式不正确");
            ResponseUtil.write(response, HttpStatus.BAD_REQUEST.value(), validResult);
        }

        if (BlankUtil.isBlank(username)) {
            validResult.fail("username", "NotBlank", "账号不能为空");
            ResponseUtil.write(response, HttpStatus.BAD_REQUEST.value(), validResult);
        }
        if (BlankUtil.isBlank(password)) {
            validResult.fail("password", "NotBlank", "密码不能为空");
            ResponseUtil.write(response, HttpStatus.BAD_REQUEST.value(), validResult);
        }
        //password = SecurityUtils.encryptPassword(password);
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,EncryptUtil.encryptPassword(password), new ArrayList<>()));
    }

    /**
     * 登录成功后
     *
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
        if (jwtTokenUtil == null) {
            jwtTokenUtil = SpringUtil.getBean(JwtTokenUtil.class);
        }

        //TODO: 更新登最近一次登录时间

        final String token = jwtTokenUtil.generateToken(jwtUser.getUsername());
        response.addHeader(jwtTokenUtil.getTokenHeader(), jwtTokenUtil.getTokenPrefix() + " " + token);
        ResponseUtil.write(response, HttpStatus.OK.value(), ResultUtil.success(token));
    }

    /**
     * 登录失败
     *
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ValidResult validResult = new ValidResult();
        validResult.fail("", "Error", "账号或密码错误");
        ResponseUtil.write(response, HttpStatus.BAD_REQUEST.value(), validResult);
    }
}